import Vue from 'vue'
import VueRouter from 'vue-router'
import Login from '@/views/login'
import Register from '@/views/register'
import Layout from '@/views/layout'
import MyCz from '@/views/MyCz.vue'
import MyLike from '@/views/MyLike.vue'
import CityList from '@/views/CityList.vue'
import { getToken } from '@/utils/storage'

// import { getToken } from '@/utils/storage'
// 导入二级路由
import Article from '@/views/article'
import House from '@/views/house.vue'
import Information from '@/views/information.vue'
import MyHouse from '@/views/MyHouse.vue'
import MyLogin from '@/views/MyLogin.vue'
import FbFy from '@/views/FbFy.vue'
// 导入二级路由下的路由
Vue.use(VueRouter)

const router = new VueRouter({
  routes: [
    { path: '/login', component: Login },
    { path: '/register', component: Register },
    {
      path: '/',
      component: Layout,
      redirect: '/article',
      children: [{
        path: 'article',
        component: Article
      },
      {
        path: '/house',
        component: House
      },
      {
        path: '/information',
        component: Information
      },
      {
        path: '/myhouse',
        component: MyHouse
      },
      {
        path: 'mylogin',
        component: MyLogin
      },
      // 我的出租
      {
        path: 'mycz',
        component: MyCz
      }
      ]
    },
    {
      path: '/fbfy',
      component: FbFy
    },
    {
      path: '/mylike',
      component: MyLike
    },
    // 城市列表
    {
      path: '/citylist',
      component: CityList
    }
  ]
})
const whiteList = ['/login', '/register']
// to:去哪里,from:哪里来,next:是否放行 next是一个函数,调用则放行
router.beforeEach((to, from, next) => {
  const token = getToken()
  if (token) {
    // 如果有token则放行去其他页面
    next()
  } else if (whiteList.includes(to.path)) {
    // 判断此时页面在不在白名单中的页面，如果在，则方向
    next()
  } else {
    next('/login') // 如果不在白名单也没有token则 跳转到指定地址
  }
})
export default router
